package com.googlecode.garbagecan.test.socket.sample7;

import com.googlecode.garbagecan.test.socket.IOUtil;

import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Logger;

public class MyClient {

	private final static Logger logger = Logger.getLogger(MyClient.class.getName());

	private String host;
	private int port;
	private boolean enableSSL;

	private Socket socket;
	private ObjectOutputStream oos = null;
	private ObjectInputStream ois = null;

	public MyClient(String host, int port, boolean enableSSL) {
		this.host = host;
		this.port = port;
		this.enableSSL = enableSSL;
	}

	public void connect() throws Exception {
		if (enableSSL) {
			System.setProperty("javax.net.ssl.trustStore", MyClient.class.getResource("/com/googlecode/garbagecan/test/socket/ssl/mysocket.jks").getFile());
			System.setProperty("javax.net.ssl.trustStorePassword", "mysocket");
			SocketFactory factory = SSLSocketFactory.getDefault();
			socket = factory.createSocket(host, port);
		} else {
			socket = new Socket(host, port);
		}

		oos = new ObjectOutputStream(socket.getOutputStream());
		ois = new ObjectInputStream(socket.getInputStream());
	}

	public void close() throws Exception {
		IOUtil.closeQuietly(ois);
		IOUtil.closeQuietly(oos);
		IOUtil.closeQuietly(socket);
	}

	public void execute() throws Exception {
		long idx = System.currentTimeMillis();
		User user = new User("user_" + idx, "password_" + idx);
		oos.writeObject(user);
		oos.flush();

		Object obj = ois.readObject();
		if (obj != null) {
			user = (User)obj;
			System.out.println("user: " + user.getName() + "/" + user.getPassword());
		}
	}

	public boolean ping() {
		try {
			execute();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
